import axios from "axios";
import { Message, MessageBox } from "element-ui";
import store from "../store";
axios.defaults.timeout = 600000;
import Vue from "vue";
let loading
axios.interceptors.request.use(
  (config) => {
    const requestConfig = config;
    if (store.state.token) {
      requestConfig.params = requestConfig.params || {}
      requestConfig.params.token = `${store.state.token}`;
      requestConfig.params.plat = `web`;
    }
    loading = Vue.prototype.$loading({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    return requestConfig;
  },
  (err) => {
    console.log(err);
    loading.close()
    return Promise.reject(err);
  }
);

axios.interceptors.response.use(
  (response) => {
    if (response.data.result === 12) {
      loading.close()
      return MessageBox.alert('您的登录已经失效，点击确定重新登录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        window.location.href = '/admin/#/'
      }).catch(() => {
        return Promise.reject();
      });
    } 
    if (response.data.result === 0) {
      loading.close()
      return response.data;
    } else {
      loading.close()
      Message.error(response.data.msg || "出错了~");
      return Promise.reject();
    }
  },
  (error) => {
    console.log(111, error);
    Message.error(error.message || error.msg || "出错了~");
    return Promise.reject(error);
  }
);

export default axios;
